package com.oswift.gpm.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.transaction.annotation.Transactional;

import com.oswift.gpm.dao.ContacterDao;
import com.oswift.gpm.dao.GroupDao;
import com.oswift.gpm.dao.RoleDao;
import com.oswift.gpm.dao.SystemDao;
import com.oswift.gpm.dao.UserDao;
import com.oswift.gpm.entity.GroupBean;
import com.oswift.gpm.entity.PageBean;
import com.oswift.gpm.entity.RelationBean;
import com.oswift.gpm.entity.RoleBean;
import com.oswift.gpm.entity.SystemModuleBean;
import com.oswift.gpm.entity.UserBean;
import com.oswift.gpm.entity.UserRGroupBean;
import com.oswift.gpm.entity.UserRRoleBean;
import com.oswift.gpm.service.IUserService;
import com.oswift.gpm.utils.PageCode;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.exception.ErrorCode;
import com.oswift.utils.exception.PlatException;

/**
 *
 * 权限管理用户的业务处理类
 *
 * @author zhuou
 * @version C03 2013-6-16
 * @since OSwift GPM V1.0
 */
public class UserServiceImpl implements IUserService
{
    /**
     * UserDao spring实例注入
     */
    private UserDao userDao;

    /**
     * ContacterDao spring实例注入
     */
    private ContacterDao contacterDao;

    /**
     * SystemDao spring注入实例
     */
    private SystemDao systemDao;

    /**
     * RoleDao spring注入实例
     */
    private RoleDao roleDao;

    /**
     * GroupDao spring注入实例
     */
    private GroupDao groupDao;

    /**
     *
     * 添加用户信息
     *
     * @author zhuou
     * @param bean
     *            用户bean
     * @return boolean
     * @throws PlatException
     *             公共平台异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean addUser(UserBean bean, String sysId) throws PlatException
    {
        try
        {
            int result = userDao.add(bean);
            if (result <= 0)
            {
                return false;
            }
            result = contacterDao.add(bean);
            if (result <= 0)
            {
                // 抛出异常回滚
                throw new PlatException(ErrorCode.COMMON_DB_ERROR);
            }
            // 如果用户选择了所属系统则执行插入t_gpm_r_usersystem操作
            if (!StringUtil.isEmpty(sysId))
            {
                String[] ids = sysId.split(",");
                List<RelationBean> list = new ArrayList<RelationBean>();
                for (String s : ids)
                {
                    RelationBean rBean = new RelationBean();
                    rBean.setAId(Integer.valueOf(s));
                    rBean.setMId(bean.getUserId());
                    list.add(rBean);
                }
                result = systemDao.addUserRSys(list);
                if (result <= 0)
                {
                    // 抛出异常回滚
                    throw new PlatException(ErrorCode.COMMON_DB_ERROR);
                }
            }
            return true;
        }
        catch (Exception e)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR, e);
        }
    }

    /**
     *
     * 获取有分页的用户列表
     *
     * @author zhuou
     * @param pageRecordNum
     * @param pageNum
     * @return PageBean
     * @throws PlatException
     *             公共平台异常
     */
    public PageBean getUserList(int pageRecordNum, int pageNum)
        throws PlatException
    {
        int rowNum = (pageNum - 1) * pageRecordNum;

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("rowNum", rowNum);
        param.put("pageNum", pageRecordNum);

        try
        {
            List<UserBean> list = userDao.selectList(param);
            int totalRecordNum = userDao.selectCount(null);
            PageBean bean = new PageBean();
            bean.setTotalRecordNum(totalRecordNum);
            bean.setDataList(list);
            return bean;
        }
        catch (Exception e)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR, e);
        }
    }

    /**
     *
     * 根据UserId查询用户详情
     *
     * @author zhuou
     * @param userId
     * @return UserBean
     * @throws PlatException
     *             公共平台异常
     */
    public UserBean getUserDetail(int userId) throws PlatException
    {
        try
        {
            UserBean bean = userDao.selectOne(userId);
            return bean;
        }
        catch (Exception e)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR, e);
        }
    }

    /**
     *
     * 根据userId查询和此用户关联的系统
     *
     * @author zhuou
     * @param userId
     *            用户Id
     * @return List<SystemModuleBean>
     * @throws PlatException
     *             公共异常
     */
    public List<SystemModuleBean> getSysByUserId(String userId)
        throws PlatException
    {
        try
        {
            List<SystemModuleBean> beans = userDao.getSysByUserId(userId);
            return beans;
        }
        catch (Exception e)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR, e);
        }
    }

    /**
     *
     * 修改用户
     *
     * @author zhuou
     * @param bean
     *            用户bean
     * @param sysId
     *            系统id字符串集合
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    public boolean updateUser(UserBean bean, String sysId) throws PlatException
    {
        try
        {
            // 根据userId删除系统和用户关系表数据
            userDao.delUserRSysByUId(String.valueOf(bean.getUserId()));

            int result = userDao.update(bean);
            if (result <= 0)
            {
                throw new PlatException(PageCode.USER_UPDATE_FAIL);
            }
            result = contacterDao.update(bean);
            if (result <= 0)
            {
                // 抛出异常回滚
                throw new PlatException(PageCode.USER_UPDATE_FAIL);
            }

            // 如果用户选择了所属系统则执行插入t_gpm_r_usersystem操作
            if (!StringUtil.isEmpty(sysId))
            {
                String[] ids = sysId.split(",");
                List<RelationBean> list = new ArrayList<RelationBean>();
                for (String s : ids)
                {
                    RelationBean rBean = new RelationBean();
                    rBean.setAId(Integer.valueOf(s));
                    rBean.setMId(bean.getUserId());
                    list.add(rBean);
                }
                result = systemDao.addUserRSys(list);
                if (result <= 0)
                {
                    // 抛出异常回滚
                    throw new PlatException(ErrorCode.COMMON_DB_ERROR);
                }
            }
            return true;
        }
        catch (Exception e)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR, e);
        }
    }

    /**
     *
     * 根据UserId删除用户
     *
     * @author zhuou
     * @param userId
     *            用户Id
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean delUser(String userId) throws PlatException
    {
        UserBean bean = userDao.selectOne(userId);
        if (null == bean)
        {
            throw new PlatException(PageCode.OPSINFO_DELETED, ResourceManager
                    .getValue(PageCode.OPSINFO_DELETED));
        }

        // 根据userId删除用户和组关联表数据
        userDao.delUserRGroupByUId(userId);

        // 根据userId删除用户和角色关联表数据
        userDao.delUserRRoleByUId(userId);

        // 根据userId删除用户和系统关联表数据
        userDao.delUserRSysByUId(userId);

        // 删除用户扩展表
        contacterDao.delete(userId);

        return userDao.delete(userId) > 0 ? true : false;
    }

    /**
     *
     * 根据userId修改用户状态
     *
     * @author zhuou
     * @param userId
     *            用户Id
     * @param status
     *            状态
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    public boolean updateUserStatus(int userId, int status)
        throws PlatException
    {
        return userDao.updateUserStatus(userId, status) > 0 ? true : false;
    }

    /**
     *
     * 获取初始化权限设置页面数据
     *
     * @author zhuou
     * @param userId
     *            用户Id
     * @param systemId
     *            角色Id
     * @return Map
     * @throws PlatException
     *             公共异常
     */
    public Map<String, Object> getSettingsRightData(int userId, int systemId)
        throws PlatException
    {
        List<RoleBean> roles = roleDao
                .getRolesBySysId(String.valueOf(systemId));

        List<GroupBean> groups = groupDao.selectList(systemId);

        List<UserRGroupBean> userRGroup = userDao.getUserRGroupByUId(userId,
                systemId);
        List<UserRRoleBean> userRRole = userDao.getUserRRoleByUId(userId,
                systemId);

        if (null != roles && !roles.isEmpty() && null != userRRole
                && !userRRole.isEmpty())
        {
            for (RoleBean item1 : roles)
            {
                for (UserRRoleBean item2 : userRRole)
                {
                    if (item1.getRoleId() == item2.getRoleId())
                    {
                        item1.setChecked(true);
                        break;
                    }
                }
            }
        }

        if (null != groups && !groups.isEmpty() && null != userRGroup
                && !userRGroup.isEmpty())
        {
            for (GroupBean item1 : groups)
            {
                for (UserRGroupBean item2 : userRGroup)
                {
                    if (item1.getGroupId() == item2.getGroupId())
                    {
                        item1.setChecked(true);
                        break;
                    }
                }
            }
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("role", roles);
        map.put("group", groups);

        return map;
    }

    /**
     *
     * 设置用户权限
     *
     * @author zhuou
     * @param userId
     *            用户Id
     * @param systemId
     *            系统Id
     * @param aRoleId
     *            角色id字符串集合
     * @param aGroupId
     *            组id字符串集合
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean settingRight(int userId, int systemId, String aRoleId,
            String aGroupId) throws PlatException
    {
        // 先删除和用户关联的权限数据
        userDao.delUserRGroupByUIdAndSysId(userId, systemId);
        userDao.delUserRRoleByUIdAndSysId(userId, systemId);

        if (!StringUtil.isEmpty(aRoleId))
        {
            String[] ids = aRoleId.split(",");
            List<UserRRoleBean> list = new ArrayList<UserRRoleBean>();
            for (String s : ids)
            {
                UserRRoleBean item = new UserRRoleBean();
                item.setRoleId(Integer.valueOf(s));
                item.setSystemId(systemId);
                item.setUserId(userId);
                list.add(item);
            }

            int rows = userDao.addUserRRole(list);
            if (rows <= 0)
            {
                throw new PlatException(ErrorCode.COMMON_DB_ERROR);
            }
        }

        if (!StringUtil.isEmpty(aGroupId))
        {
            String[] ids = aGroupId.split(",");
            List<UserRGroupBean> list = new ArrayList<UserRGroupBean>();
            for (String s : ids)
            {
                UserRGroupBean item = new UserRGroupBean();
                item.setGroupId(Integer.valueOf(s));
                item.setSystemId(systemId);
                item.setUserId(userId);
                list.add(item);
            }

            int rows = userDao.addUserRGroup(list);
            if (rows <= 0)
            {
                throw new PlatException(ErrorCode.COMMON_DB_ERROR);
            }
        }
        return true;
    }

    public void setUserDao(UserDao userDao)
    {
        this.userDao = userDao;
    }

    public void setContacterDao(ContacterDao contacterDao)
    {
        this.contacterDao = contacterDao;
    }

    public void setSystemDao(SystemDao systemDao)
    {
        this.systemDao = systemDao;
    }

    public void setRoleDao(RoleDao roleDao)
    {
        this.roleDao = roleDao;
    }

    public void setGroupDao(GroupDao groupDao)
    {
        this.groupDao = groupDao;
    }
}
